<template>
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
        <el-form-item label="账号" prop="accountName">
            <el-input v-model="ruleForm.accountName" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
            <el-input v-model="ruleForm.password" show-password />
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
                登录
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        </el-form-item>
    </el-form>
</template>
<!-- router.push({path: '/slaughter',query: {SourceId: row.id}}) -->
<script lang="ts" setup>
import { reactive, ref } from 'vue'

import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import router from '@/router'
import myAxios from '@/http/MyAxios'

interface RuleForm {
    "accountName": "",
    "password": ""
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    "accountName": "",
    "password": ""
})

const rules = reactive<FormRules<RuleForm>>({
    accountName: [
        { required: true, message: '账号不能为空', trigger: 'blur' },
    ],
    password: [
        {
            required: true,
            message: '密码不能为空',
            trigger: 'blur',
        },
    ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            myAxios.post("/api/Source/LoginAccount", ruleForm).then(res => {
                if (res.data.code == 10200) {
                    ElMessage.success(res.data.message)
                    window.sessionStorage.setItem("token", res.data.data.token);
                    window.sessionStorage.setItem("AccountId", res.data.data.id);
                    window.sessionStorage.setItem("accountName", res.data.data.accountName);
                    window.sessionStorage.setItem("roleName", res.data.data.roleName);
                    // 数据提交后端要加入新的Token值
                    myAxios.defaults.headers.common["Authorization"] =
                        "Bearer " + res.data.token;
                    router.push("/main")
                }
                else {
                    ElMessage.error(res.data.message)
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

</script>
